<template>
  <div class="clothes-list-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <span class="page-title">我的衣橱</span>
        <div @click="handleFilterClick" class="filter-icon-container">
          <van-badge :content="filterCount" :show-zero="false" color="#6c63ff">
            <img
              src="/src/assets/icons/filter.svg"
              alt="筛选"
              width="20"
              height="20"
            />
          </van-badge>
        </div>
      </div>
      <div class="search-bar">
        <van-search
          v-model="searchKeyword"
          placeholder="搜索衣物标签"
          show-action
          shape="round"
          clear-trigger="always"
          @search="handleSearch"
          @clear="handleClearSearch"
        >
          <template #action>
            <div @click="handleSearch">搜索</div>
          </template>
        </van-search>
      </div>
    </div>

    <!-- 分类分组的衣物展示 -->
    <div v-if="filteredClothes.length > 0 && !loading" class="clothes-grid">
      <div
        v-for="(categoryClothes, category) in groupedClothes"
        :key="category"
      >
        <!-- 分类标题 -->
        <div class="category-header" @click="goToCategoryDetail(category)">
          <div class="category-info">
            <img
              :src="`/src/assets/icons/${getCategoryIcon(category)}`"
              alt="分类图标"
              width="20"
              height="20"
            />
            <!-- <span class="category-icon">{{ getCategoryIcon(category) }}</span> -->
            <span class="category-name">{{ category }}</span>
          </div>
          <div class="category-count">
            <span style="margin-right: 8px"> {{ categoryClothes.length }}</span>
            <van-icon name="arrow" />
          </div>
        </div>

        <!-- 衣物图片网格 -->
        <ClothesImage :clothes="categoryClothes" />
      </div>
    </div>

    <!-- 空状态 -->
    <div
      v-else-if="filteredClothes.length === 0 && !loading"
      class="empty-state"
    >
      <img src="/src/assets/icons/empty.svg" alt="" style="width: 40%" />
      <p>您的衣橱还是空的</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <van-loading type="spinner" />衣物加载中...
    </div>

    <!-- 右侧筛选组件 -->
    <FilterSidebar
      v-model:show="showFilterSidebar"
      :categories="categoriesForFilter"
      @apply="handleFilterApply"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useClothesStore } from "../store/clothes";
import { useUserStore } from "../store/user";
import { getCategoryIcon } from "../utils/clothesCategory";
import ClothesImage from "../components/ClothesImage.vue";
import FilterSidebar from "../components/FilterSidebar.vue";

const router = useRouter();
const clothesStore = useClothesStore();
const userStore = useUserStore();

// 搜索关键词
const searchKeyword = ref("");
// 实际用于筛选的搜索关键词
const activeSearchKeyword = ref("");

// 筛选条件
const selectedSeasons = ref([]);
const selectedColors = ref([]);
const selectedCategories = ref([]);

const loading = ref(false);
const showFilterSidebar = ref(false);

// 筛选条件数量
const filterCount = ref(0);

// 计算筛选后的衣物列表
const filteredClothes = computed(() => {
  let filtered = clothesStore.clothesList;

  // 按季节筛选
  if (selectedSeasons.value.length > 0) {
    filtered = filtered.filter(
      (item) =>
        item.season?.some((season) => selectedSeasons.value.includes(season)) ||
        false
    );
  }

  // 按颜色筛选
  if (selectedColors.value.length > 0) {
    console.log(selectedColors.value);

    filtered = filtered.filter((item) =>
      selectedColors.value.includes(item.color)
    );
  }

  // 按分类筛选
  if (selectedCategories.value.length > 0) {
    filtered = filtered.filter((item) => {
      let categoryName = item.type;
      if (
        Array.isArray(item.type) &&
        item.type.length > 0 &&
        item.type[0].text
      ) {
        categoryName = item.type[0].text;
      }
      return selectedCategories.value.includes(categoryName);
    });
  }

  // 按关键词搜索
  if (activeSearchKeyword.value.trim()) {
    const keyword = activeSearchKeyword.value.toLowerCase().trim();
    filtered = filtered.filter((item) =>
      item.name.toLowerCase().includes(keyword)
    );
  }

  return filtered;
});

// 按分类分组衣物
const groupedClothes = computed(() => {
  // 如果filteredClothes为空，直接返回空对象
  if (filteredClothes.value.length === 0) {
    return {
      上衣: [],
      下装: [],
      鞋子: [],
      裙子: [],
      外套: [],
      配饰: [],
      运动装: [],
      家居服: [],
    };
  }
  // 定义用户要求的固定排序
  const orderedCategories = [
    "上衣",
    "下装",
    "鞋子",
    "裙子",
    "外套",
    "配饰",
    "运动装",
    "家居服",
  ];
  const groups = {};

  // 先创建空数组以确保顺序
  orderedCategories.forEach((category) => {
    groups[category] = [];
  });

  filteredClothes.value.forEach((item) => {
    // 确保处理用户提供的数据结构，只取索引为0的text值作为分类名称
    let categoryName = item.type;
    if (Array.isArray(item.type) && item.type.length > 0 && item.type[0].text) {
      categoryName = item.type[0].text;
    }

    // 只有在预定义的分类中才添加
    if (orderedCategories.includes(categoryName)) {
      groups[categoryName].push(item);
    }
  });

  // 过滤掉空分类
  const filteredGroups = {};
  for (const category of orderedCategories) {
    if (groups[category].length > 0) {
      filteredGroups[category] = groups[category];
    }
  }

  return filteredGroups;
});

// 给筛选组件传递分类数据
const categoriesForFilter = computed(() => {
  // 定义用户要求的固定排序
  const orderedCategories = [
    "上衣",
    "下装",
    "鞋子",
    "裙子",
    "外套",
    "配饰",
    "运动装",
    "家居服",
  ];
  const groups = {};

  // 先创建空数组以确保顺序
  orderedCategories.forEach((category) => {
    groups[category] = [];
  });

  clothesStore.clothesList.forEach((item) => {
    // 确保处理用户提供的数据结构，只取索引为0的text值作为分类名称
    let categoryName = item.type;
    if (Array.isArray(item.type) && item.type.length > 0 && item.type[0].text) {
      categoryName = item.type[0].text;
    }

    // 只有在预定义的分类中才添加
    if (orderedCategories.includes(categoryName)) {
      groups[categoryName].push(item);
    }
  });

  // 过滤掉空分类
  const filteredGroups = {};
  for (const category of orderedCategories) {
    if (groups[category].length > 0) {
      filteredGroups[category] = groups[category];
    }
  }

  return filteredGroups;
});

// 处理筛选结果
const handleFilterApply = (filters) => {
  selectedSeasons.value = filters.seasons;
  selectedCategories.value = filters.categories;
  selectedColors.value = filters.colors;
  // 更新筛选条件数量
  filterCount.value = Object.keys(filters).filter(
    (key) => filters[key].length > 0
  ).length;
};

// 处理筛选组件点击
const handleFilterClick = () => {
  showFilterSidebar.value = true;
};

// 导航到分类详情页面
const goToCategoryDetail = (category) => {
  router.push({
    path: "/clothes/category",
    query: { name: category },
  });
};

// 搜索
const handleSearch = () => {
  activeSearchKeyword.value = searchKeyword.value;
};

// 清除搜索
const handleClearSearch = () => {
  searchKeyword.value = "";
  activeSearchKeyword.value = "";
};

// 加载衣物数据
const loadClothes = async () => {
  try {
    loading.value = true;
    await clothesStore.fetchClothesList();
  } catch (error) {
    console.error("加载衣物数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 页面挂载时加载数据
onMounted(() => {
  loadClothes();
});
</script>

<style scoped>
.clothes-list-container {
  height: 100vh;
  /* background-color: #f5f5f5; */
  padding: 0px 0px 70px 0px;
  display: flex;
  flex-direction: column;
}

.page-header {
  background-color: #ffffff;
  border-radius: 0 0 16px 16px;
  padding: 20px;
}
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header .page-title {
  font-size: 16px;
  font-weight: bold;
  color: #000000;
}

.add-button {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  text-decoration: none;
  border-radius: 8px;
  font-size: 14px;
}

.add-button .van-icon {
  margin-right: 5px;
}

.filter-icon-container {
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: background-color 0.3s;
}

.filter-icon-container:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.filter-section {
  background: white;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.search-bar {
  margin-top: 20px;
}
.van-search {
  padding: 0;
}
.van-cell {
  height: 40px;
}
.clothes-grid {
  padding: 0 20px;
  flex: 1;
  overflow-y: auto;
  /* 隐藏滚动条 */
  scrollbar-width: none;
  -ms-overflow-style: none;
  /* 兼容h5 */
  overflow: -moz-scrollbars-none;
}
.clothes-grid::-webkit-scrollbar {
  display: none;
}
/* 分类标题样式 */
.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
}

.category-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.category-icon {
  font-size: 18px;
}

.category-name {
  font-size: 16px;
  /* font-weight: 600; */
  color: #000000;
}

.category-count {
  font-size: 14px;
  color: #000000;
}

.empty-state {
  text-align: center;
  padding: 60px 0px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-state p {
  color: #666;
  margin: 5px 0;
}

.empty-hint {
  font-size: 14px;
  color: #999;
}

.loading-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.van-checkbox {
  margin-top: 10px;
}
</style>
